package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasFormSubDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.saas.feign.WorkOrderV2CommonFeignClient;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.pojo.vo.PrePayBalanceListVO;
import com.xbongbong.paas.pojo.vo.PrePaymentBalanceListVO;
import com.xbongbong.paas.service.ExcelDataService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.CommentHelp;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.ExportErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.knowledge.base.pojo.dto.KnowledgeListDTO;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.PayBalanceEntity;
import com.xbongbong.saas.domain.entity.PaymentBalanceEntity;
import com.xbongbong.saas.domain.entity.ProductSubDataEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.BatchFlowBillEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.DistributorCommunicateEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.StockFlowBillEnum;
import com.xbongbong.saas.enums.business.SupplierCommunicateEnum;
import com.xbongbong.saas.help.ProductListHelp;
import com.xbongbong.saas.model.CompetitorModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductSubDataModel;
import com.xbongbong.saas.model.ScoreRangeModel;
import com.xbongbong.saas.service.CreditLimitService;
import com.xbongbong.saas.service.CreditTemporaryLimitService;
import com.xbongbong.saas.service.PayBalanceService;
import com.xbongbong.saas.service.PaymentBalanceService;
import com.xbongbong.saas.service.PriceSetService;
import com.xbongbong.saas.service.SaasListService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author 吴峰
 * @date 2022/08/04 15:38
 */
@Service("excelDataService")
public class ExcelDataServiceImpl implements ExcelDataService {

    private static final Logger LOG = LoggerFactory.getLogger(ExcelDataServiceImpl.class);

    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private SaasListService saasListService;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PaymentBalanceService paymentBalanceService;
    @Resource
    private ProductListHelp productListHelp;
    @Resource
    private PayBalanceService payBalanceService;
    @Resource
    private PriceSetService priceSetService;
    @Resource
    private CreditTemporaryLimitService creditTemporaryLimitService;
    @Resource
    private CreditLimitService creditLimitService;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private ScoreRangeModel scoreRangeModel;
    @Resource
    private ProductSubDataModel productSubDataModel;
    @Resource
    private CompetitorModel competitorModel;

    @Resource
    private WorkOrderV2CommonFeignClient workOrderV2CommonFeignClient;

    @Override
    public PaasFormDataEsListVO getSaasDataList(FormDataListDTO formDataListDTO, Integer businessType, Integer subBusinessType, XbbRefTypeEnum xbbRefTypeEnum, boolean partialExportFlag) throws XbbException {
        String corpid = formDataListDTO.getCorpid();
        String userId = formDataListDTO.getUserId();

        PaasFormDataEsListVO formDataListVO = null;
        XbbRefTypeEnum subRefTypeEnum;


        formDataListDTO.setSearchSubForm(true);
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(formDataListDTO, handlerExplainDTO, false);
        switch (xbbRefTypeEnum) {
            case CONTRACT:
                formDataListVO = saasListService.contractList(formDataListDTO);
                break;
            case ORDER:
                formDataListVO = saasListService.orderList(formDataListDTO);
                break;
            case QUOTATION:
                formDataListVO = saasListService.quotationList(formDataListDTO);
                break;
            case CUSTOMER_MANAGEMENT:
                subRefTypeEnum = XbbRefTypeEnum.getByCode(formDataListDTO.getSubBusinessType());
                switch (subRefTypeEnum) {
                    case CUSTOMER:
                    case CUSTOMER_FOCUS:
                    case CUSTOMER_DEAL:
                    case CUSTOMER_FOLLOW:
                    default:
                        formDataListVO = saasListService.customerList(formDataListDTO);
                        break;
                    case CUSTOMER_PUBLIC:
                        formDataListVO = saasListService.publicCustomer(formDataListDTO);
                        break;
                    case CUSTOMER_RECYCLE:
                        formDataListVO = saasListService.delCustomerList(formDataListDTO);
                        formDataListDTO.setDel(DelEnum.NORMAL.getDel());
                        break;
                }
                phoneExportCanSee(formDataListVO, xbbRefTypeEnum, handlerExplainDTO);
                //格式化评分，按照评分区间
                handleDataList4ScoreRange(businessType,corpid, formDataListDTO.getFormId(), formDataListVO);
                break;
            case CLUE:
                if (Objects.equals(subBusinessType, XbbRefTypeEnum.CLUE_PUBLIC.getCode())) {
                    formDataListVO = saasListService.publicClue(formDataListDTO);
                } else if (Objects.equals(subBusinessType, XbbRefTypeEnum.CLUE_RECYCLE.getCode())) {
                    formDataListVO = saasListService.delClueList(formDataListDTO);
                    formDataListDTO.setDel(DelEnum.NORMAL.getDel());
                } else {
                    formDataListVO = saasListService.clueList(formDataListDTO);
                }
                //格式化评分，按照评分区间
                handleDataList4ScoreRange(businessType,corpid, formDataListDTO.getFormId(), formDataListVO);
                break;
            case MARKET_ACTIVITY:
                formDataListVO = saasListService.marketActivityList(formDataListDTO);
                break;
            case DISTRIBUTOR_MANAGEMENT:
                formDataListVO = saasListService.distributorList(formDataListDTO);
                break;
            case DISTRIBUTOR_CONTACT:
                formDataListVO = saasListService.distributorContactList(formDataListDTO);
                break;
            case DISTRIBUTOR_ACCOUNT:
                formDataListVO = saasListService.distributorAccountList(formDataListDTO);
                break;
            case SALES_OPPORTUNITY:
                formDataListVO = saasListService.opportunityList(formDataListDTO);
                break;
            case CONTACT:
                formDataListVO = saasListService.contactList(formDataListDTO);
                break;
            case CUSTOMER_COMMUNICATE:
                formDataListVO = saasListService.customerCommunicateList(formDataListDTO);
                List<PaasFormDataEntityExt> customerCommunicateList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt entityExt : customerCommunicateList) {
                    JSONObject data = entityExt.getData();
                    if (Objects.isNull(data)) {
                        continue;
                    }
                    String memo = FastJsonHelper.getStringOrDefaultFromFormData(data, CustomerCommunicateEnum.MEMO.getAttr(), "");
                    data.put(CustomerCommunicateEnum.MEMO.getAttr(), CommentHelp.filterCommentContent(memo));
                }
                break;
            case SUPPLIER_COMMUNICATE:
                formDataListVO = saasListService.supplierCommunicateList(formDataListDTO);
                List<PaasFormDataEntityExt> supplierCommunicateList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt entityExt : supplierCommunicateList) {
                    JSONObject data = entityExt.getData();
                    if (Objects.isNull(data)) {
                        continue;
                    }
                    String memo = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierCommunicateEnum.MEMO.getAttr(), "");
                    data.put(SupplierCommunicateEnum.MEMO.getAttr(), CommentHelp.filterCommentContent(memo));
                }
                break;
            case DISTRIBUTOR_COMMUNICATE:
                formDataListVO = saasListService.distributorCommunicate4Export(formDataListDTO);
                List<PaasFormDataEntityExt> distributorCommunicateList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt entityExt : distributorCommunicateList) {
                    JSONObject data = entityExt.getData();
                    if (Objects.isNull(data)) {
                        continue;
                    }
                    String memo = data.getString(DistributorCommunicateEnum.MEMO.getAttr());
                    data.put(DistributorCommunicateEnum.MEMO.getAttr(), CommentHelp.filterCommentContent(memo));
                }
                break;
            case INVOICE:
                formDataListVO = saasListService.invoiceList(formDataListDTO);
                break;
            case PURCHASE_INVOICE:
                formDataListVO = saasListService.purchaseInvoiceList(formDataListDTO);
                break;
            case PAYMENT:
                formDataListVO = saasListService.paymentList(formDataListDTO);
                break;
            case PAY_PLAN:
                formDataListVO = saasListService.payPlanList(formDataListDTO);
                break;
            case SUPPLIER:
                formDataListVO = saasListService.supplierList(formDataListDTO);
                break;
            case SUPPLIER_CONTACT:
                formDataListVO = saasListService.supplierContactList(formDataListDTO);
                break;
            case INSTOCK:
            case OTHER_INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
                formDataListVO = saasListService.instockList(formDataListDTO);
                break;
            case OUTSTOCK:
            case OTHER_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case ORDER_OUTSTOCK:
                formDataListVO = saasListService.outstockList(formDataListDTO);
                break;
            case ASSEMBLE:
                formDataListVO = saasListService.assembleList(formDataListDTO);
                break;
            case TRANSFER:
                formDataListVO = saasListService.transferList(formDataListDTO);
                break;
            case INVENTORY:
                formDataListVO = saasListService.inventoryList(formDataListDTO);
                break;
            case RETURNED_PURCHASE:
                formDataListVO = saasListService.returnedPurchaseList(formDataListDTO);
                break;
            case PURCHASE:
                formDataListVO = saasListService.purchaseList(formDataListDTO);
                break;
            case PRODUCT:
                formDataListVO = saasListService.productListSuper(formDataListDTO);
                break;
            case BOM_BILL:
                formDataListVO = saasListService.bombillList(formDataListDTO);
                break;
            case PRODUCTION_ORDER:
                formDataListVO = saasListService.productionOrderList(formDataListDTO);
                break;
            case REFUND:
                formDataListVO = saasListService.refundList(formDataListDTO);
                break;
            case RETURN:
                formDataListVO = saasListService.returnList(formDataListDTO);
                break;
            case STOCK_SEARCH:
                formDataListDTO.setFieldList(null);
                formDataListVO = saasListService.newProductStockList(formDataListDTO);
                List<Long> dataIdList = new ArrayList<>();
                for (PaasFormDataEntityExt entity : formDataListVO.getPaasFormDataESList()) {
                    dataIdList.add(entity.getId());
                }
                dataIdList.add(-1L);
                subRefTypeEnum = XbbRefTypeEnum.getByCode(formDataListDTO.getSubBusinessType());
                Map<Long,String> productWarehouseMap;
                Map<Long, JSONArray> productSearchMap;
                switch (subRefTypeEnum) {
                    case GUARANTEE_SEARCH:
                    case WARNING_SEARCH:
                        productWarehouseMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        formDataListDTO.setProductWarehouseMap(productWarehouseMap);
                        break;
                    default:
                        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
                        Map<String, FieldAttrEntity> productExplainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);
                        List<Long> warehouseIdList = formDataListDTO.getSelectWarehouseIdList();
                        productSearchMap = productListHelp.productWarehouseList(formDataListDTO, formDataListVO.getPaasFormDataESList(), dataIdList,corpid,warehouseIdList, productExplainMap);
                        formDataListDTO.setChildProductMap(productSearchMap);
                        break;
                }
                break;
            case PAYMENT_SHEET:
                formDataListVO = saasListService.paymentSheetList(formDataListDTO);
                break;
            case PAY_SHEET:
                formDataListVO = saasListService.paySheetList(formDataListDTO);
                break;
            case ONLINE_PAYMENT_FLOW:
                formDataListVO = saasListService.onlinePaymentFlowList(formDataListDTO);
                break;
            case PREPAYMENT_BALANCE:
                formDataListDTO.setFieldList(null);
                PrePaymentBalanceListVO prePaymentBalanceListVO = paymentBalanceService.prepaymentBalanceList(formDataListDTO);
                List<PaymentBalanceEntity>  paymentBalanceList =  prePaymentBalanceListVO.getPaasFormDataESList();
                formDataListVO = new PaasFormDataEsListVO();
                BeanUtil.copyProperties(prePaymentBalanceListVO,formDataListVO);
                List<PaasFormDataEntityExt> paasFormDataESList = new ArrayList<>(paymentBalanceList.size());
                for (PaymentBalanceEntity paymentBalanceEntity : paymentBalanceList) {
                    PaasFormDataEntityExt  paasFormDataEntityExt = new PaasFormDataEntityExt();
                    BeanUtil.copyProperties(paymentBalanceEntity,paasFormDataEntityExt);
                    paasFormDataESList.add(paasFormDataEntityExt);
                }
//                    BeanUtil.copyPropertiesList(paymentBalanceList,paasFormDataESList,PaasFormDataEntityExt.class);
                formDataListVO.setPaasFormDataESList(paasFormDataESList);
                break;
            case PREPAY_BALANCE:
                formDataListDTO.setFieldList(null);
                PrePayBalanceListVO prePayBalanceListVO = payBalanceService.prepayBalanceList(formDataListDTO);
                List<PayBalanceEntity>  payBalanceList =  prePayBalanceListVO.getPaasFormDataESList();
                formDataListVO = new PaasFormDataEsListVO();
                BeanUtil.copyProperties(prePayBalanceListVO,formDataListVO);
                List<PaasFormDataEntityExt> payBalanceESList = new ArrayList<>(payBalanceList.size());
                for (PayBalanceEntity payBalanceEntity : payBalanceList) {
                    PaasFormDataEntityExt  paasFormDataEntityExt = new PaasFormDataEntityExt();
                    BeanUtil.copyProperties(payBalanceEntity,paasFormDataEntityExt);
                    payBalanceESList.add(paasFormDataEntityExt);
                }
                formDataListVO.setPaasFormDataESList(payBalanceESList);
                break;
            case STOCK_FLOW_BILL:
                formDataListVO = saasListService.stockFlowBillList(formDataListDTO);
                formDataListVO.setExplainMap(ExplainUtil.getExplainMapByList(formDataListVO.getHeadList(), null));
                formDataListVO.getExplainMap().get(StockFlowBillEnum.SHEET_NO.getAttr()).setFieldType(FieldTypeEnum.TEXT.getType());
                formDataListDTO.setExplainMap(formDataListVO.getExplainMap());
                break;
            case STOCK_STANDING_BOOK:
                formDataListVO = saasListService.stockStandingBookList(formDataListDTO);
                formDataListVO.setExplainMap(ExplainUtil.getExplainMapByList(formDataListVO.getHeadList(), null));
                formDataListDTO.setExplainMap(formDataListVO.getExplainMap());
                break;
            case BATCH_FLOW_BILL:
                formDataListVO = saasListService.batchFlowBillList(formDataListDTO);
                formDataListVO.setExplainMap(ExplainUtil.getExplainMapByList(formDataListVO.getHeadList(), null));
                formDataListVO.getExplainMap().get(BatchFlowBillEnum.SHEET_NO.getAttr()).setFieldType(FieldTypeEnum.TEXT.getType());
                formDataListDTO.setExplainMap(formDataListVO.getExplainMap());
                break;
            case SEQ_SEARCH:
                formDataListVO = saasListService.productSerialList(formDataListDTO);
                formDataListVO.setExplainMap(ExplainUtil.getExplainMapByList(formDataListVO.getHeadList(), null));
                formDataListDTO.setExplainMap(formDataListVO.getExplainMap());
                break;
            case FUND_TRANSFER:
                formDataListVO = saasListService.fundTransferList(formDataListDTO);
                break;
            case OTHER_INCOME:
                formDataListVO = saasListService.otherIncomeList(formDataListDTO);
                break;
            case OTHER_EXPENSE:
                formDataListVO = saasListService.otherExpenseList(formDataListDTO);
                break;
            case PRICE_SET_PRODUCT:
                formDataListVO = priceSetService.priceSetList(formDataListDTO);
                formDataListVO.setExplainMap(ExplainUtil.getExplainMapByList(formDataListVO.getHeadList(), null));
                formDataListDTO.setExplainMap(formDataListVO.getExplainMap());
                break;
            case MARKETING_ACTIVITY_MANAGEMENT:
                formDataListVO = saasListService.marketingActivity(formDataListDTO);
                formDataListVO.setExplainMap(ExplainUtil.getExplainMapByList(formDataListVO.getHeadList(), null));
                formDataListDTO.setExplainMap(formDataListVO.getExplainMap());
                break;
            case PROMOTION_ACTIVITY_MANAGEMENT:
                formDataListVO = saasListService.promotionActivity(formDataListDTO);
                formDataListVO.setExplainMap(ExplainUtil.getExplainMapByList(formDataListVO.getHeadList(), null));
                formDataListDTO.setExplainMap(formDataListVO.getExplainMap());
                break;
            case WRITE_OFF_RECORD:
                formDataListVO = saasListService.writeOffRecord(formDataListDTO);
                formDataListVO.setExplainMap(ExplainUtil.getExplainMapByList(formDataListVO.getHeadList(), null));
                formDataListDTO.setExplainMap(formDataListVO.getExplainMap());
                break;
            case CREDIT_LIMIT:
                formDataListVO = saasListService.creditLimitList(formDataListDTO);
                // 计算各种额度
                creditLimitService.formatExportValueBefore(formDataListVO.getPaasFormDataESList(), formDataListDTO);
                break;
            case CREDIT_TEMPORARY_LIMIT:
                formDataListVO = saasListService.creditTemporaryLimitList(formDataListDTO);
                creditTemporaryLimitService.formatExportValueBefore(formDataListVO.getPaasFormDataESList(), formDataListDTO);
                break;
            case CREDIT_FIXED_LIMIT:
                formDataListVO = saasListService.creditFixedLimitList(formDataListDTO);
                break;
            case WAIT_INSTOCK_PURCHASE:
                formDataListDTO.setFromExport(0);
                formDataListVO = saasListService.waitInstockList(formDataListDTO);
                break;
            case WAIT_OUTSTOCK:
                formDataListDTO.setFromExport(0);
                formDataListVO = saasListService.waitOutstockList(formDataListDTO);
                break;
            case WAIT_PURCHASE:
                formDataListDTO.setFromExport(0);
                formDataListVO = saasListService.waitPurchaseList(formDataListDTO);
                break;
            case SMART_REPLENISHMENT:
                formDataListDTO.setFromExport(0);
                formDataListVO = saasListService.smartReplenishment(formDataListDTO);
                break;
            case COST_ADJUST:
                formDataListVO = saasListService.costAdjustList(formDataListDTO);
                break;
            case KNOWLEDGE_BASE:
                KnowledgeListDTO knowledgeListDTO=new KnowledgeListDTO();
                BeanUtil.copyProperties(formDataListDTO,knowledgeListDTO);
                formDataListVO = saasListService.knowledgeList(knowledgeListDTO);
                formDataListVO.setExplainMap(ExplainUtil.getExplainMapByList(formDataListVO.getHeadList(), null));
                formDataListDTO.setExplainMap(formDataListVO.getExplainMap());
                break;
            case COMPETITOR:
                formDataListVO = saasListService.competitorList(formDataListDTO);
                break;
            case WORK_ORDER_V2:
            case SLA_LOG:
            case RECEIPT_ORDER:
            case SERVICE_PROJECT:
                try {
                    String str = workOrderV2CommonFeignClient.list(formDataListDTO, LocaleContextHolder.getLocale().toString());
                    XbbResponse  response = JSONObject.parseObject(str,XbbResponse.class);
                    if (!response.isSuccess()) {
                        throw new XbbException(response.getCode(), response.getMsg());
                    }
                    JSONObject result  = (JSONObject) response.getResult();
                    formDataListVO =  JSONObject.parseObject(result.toJSONString(),PaasFormDataEsListVO.class);
                } catch (Exception e) {
                    LOG.error("工单v2服务导出失败",e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                break;
            default:
                formDataListVO = new PaasFormDataEsListVO();
                break;
        }
        if (formDataListVO.getPaasFormDataESList().isEmpty()) {
            return formDataListVO;
        }
        // 子表单数据查询
        IndexTypeEnum indexTypeEnum;
        boolean isStockSearch = Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.STOCK_SEARCH);
        if(Objects.equals(formDataListDTO.getSaasMark(), SaasMarkEnum.PAAS.getCode())){
            indexTypeEnum = IndexTypeEnum.IDX_FORM_DATA;
        }else{
            if(businessType == null || businessType.equals(0)){
                LOG.error("businessType为空");
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            businessType = isStockSearch ? XbbRefTypeEnum.PRODUCT.getCode() : businessType;
            indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, formDataListDTO.getSaasMark());
        }
        if (indexTypeEnum != null && indexTypeEnum != IndexTypeEnum.UNKNOWN) {
            if (isStockSearch) {
                Set<Long> set = new HashSet<>();
                formDataListVO.getPaasFormDataESList().forEach(item->{
                    if (Objects.nonNull(item.getData().get(ProductEnum.PARENT_ID.getAttr()))) {
                        set.add(item.getData().getLong(ProductEnum.PARENT_ID.getAttr()));
                    }
                });
                List<ProductSubDataEntity> productSubDataEntities = productSubDataModel.getByDataIds(set, corpid, DelEnum.NORMAL);
                Map<Long, Map<String, JSONArray>> subMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (PaasFormSubDataEntity subDataEntity : productSubDataEntities) {
                    JSONObject data = subDataEntity.getData();
                    data.put(BusinessConstant.SUB_DATA_ID, subDataEntity.getId());
                    subDataEntity.setData(data);
                    subMap.computeIfAbsent(subDataEntity.getDataId(), v -> new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY)).computeIfAbsent(subDataEntity.getAttr(), v -> new JSONArray()).add(data);
                }
                formDataListVO.getPaasFormDataESList().forEach(item->{
                    if (Objects.nonNull(item.getData().get(ProductEnum.PARENT_ID.getAttr()))) {
                        Map<String, JSONArray> subData = subMap.get(item.getData().getLong(ProductEnum.PARENT_ID.getAttr()));
                        if (Objects.nonNull(subData)) {
                            subData.forEach((k, v) -> {
                                if (Objects.nonNull(item.getData())) {
                                    // 这里将子表单进行序列化放进新的内存中，避免多规格解析子表单出问题；
                                    JSONArray copyArray = JSONArray.parseArray(JSON.toJSONString(v));
                                    item.getData().put(k, copyArray);
                                }
                            });
                        }
                    }
                });
            } else {
                paasFormSubDataModel.findSubEntity(corpid, formDataListVO.getPaasFormDataESList(), IndexTypeEnum.getSubByIndexEnum(indexTypeEnum));
                if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_INVOICE)) {
                    paasFormSubDataModel.findSubEntity(corpid, formDataListVO.getPaasFormDataESList(), IndexTypeEnum.IDX_SAAS_INVOICE_EXPRESS);
                }
                if (Objects.equals(indexTypeEnum, IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE)) {
                    paasFormSubDataModel.findSubEntity(corpid, formDataListVO.getPaasFormDataESList(), IndexTypeEnum.IDX_SAAS_PURCHASE_INVOICE_EXPRESS);
                }
            }

        }
        //如果是部分导出，超过10000条数据选择合并单元格，抛出异常
        boolean mergeCellsFlag = false;
        if (partialExportFlag){
            mergeCellsFlag =  Objects.equals(formDataListDTO.getExcelPartialExportPojo().getMergeCells(),1) && formDataListVO.getPaasFormDataESList().size() > 10000;
            if (mergeCellsFlag){
                //超过10000条数据选择合并单元格，抛出异常
                throw new XbbException(ExportErrorCodeEnum.API_ERROR_234008);
            }
        }

        return formDataListVO;
    }

    /**
     * 导出时，按照评分区间来
     */
    private void handleDataList4ScoreRange(Integer businessType,String corpid, Long formId, PaasFormDataEsListVO paasFormDataEsListVO){
        if(XbbRefTypeEnum.checkScoreBusinessType(businessType) && Objects.nonNull(paasFormDataEsListVO) && CollectionsUtil.isNotEmpty(paasFormDataEsListVO.getPaasFormDataESList())){
            List<PaasFormDataEntityExt> paasFormDataESList = paasFormDataEsListVO.getPaasFormDataESList();
            try {
                scoreRangeModel.getScoreShowValueByList(businessType, corpid, formId, paasFormDataESList);
            }catch (Exception e){
                LOG.error("handleDataList4ScoreRange 异常{}",e.getMessage());
            }
        }
    }

    /**
     * 导出号码进行脱敏处理
     * @author youli.chen
     *
     */
    private void phoneExportCanSee(PaasFormDataEsListVO formDataListVO, XbbRefTypeEnum xbbRefTypeEnum, HandlerExplainDTO handlerExplainDTO) throws XbbException{
        if (formDataListVO.getPaasFormDataESList().isEmpty()) {
           return;
        }
        boolean isShow = false;
        JSONArray phoneJsonArray = null;
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMapByList(formDataListVO.getHeadList());

        List<PaasFormDataEntityExt> paasFormDataEntityExt = formDataListVO.getPaasFormDataESList();

        switch (xbbRefTypeEnum) {
            case CUSTOMER_MANAGEMENT:
                handlerExplainDTO.setExplainList(formDataListVO.getHeadList());
                handlerExplainDTO.setPaasFormEntityExt(formDataListVO.getForm());

                for(PaasFormDataEntityExt customerEs : paasFormDataEntityExt){
                    handlerExplainDTO.setCreatorId(customerEs.getCreatorId());

                    JSONObject dataList = customerEs.getData();
                    if (Objects.isNull(dataList)) {
                        continue;
                    }
                    phoneJsonArray = dataList.getJSONArray(CustomerManagementEnum.PHONE.getAttr());
                    boolean attrVisible = commonHelp.attrCanSee(CustomerManagementEnum.PHONE.getAttr(), explainMap, handlerExplainDTO);
                    if(attrVisible){
                        List<? extends FieldAttrEntity> explainSubFormList = explainMap.get(CustomerManagementEnum.PHONE.getAttr()).getSubForm().getItems();
                        Map<String, FieldAttrEntity> explainSubFormMap = new HashMap<>(explainSubFormList.size());
                        explainSubFormList.forEach((item) -> explainSubFormMap.put(item.getAttr(), item));
                        boolean text2CanSee = commonHelp.attrCanSee(StringConstant.PHONE_TEL_ATTR, explainSubFormMap, handlerExplainDTO);
                        if(text2CanSee){
                            isShow = true;
                        }
                    }
                    phoneJsonArray = Objects.isNull(phoneJsonArray) ? new JSONArray() : phoneJsonArray;
                    for (int i = 0; i < phoneJsonArray.size(); i++) {
                        String tel = phoneJsonArray.getJSONObject(i).getString("text_2");
                        if (!isShow && tel != null) {
                            String telNum;
                            if (tel.length() > 5) {
                                telNum = tel.substring(0, 3) + "****" + tel.substring(tel.length() - 2, tel.length());
                            } else {
                                telNum = "*****";
                            }
                            phoneJsonArray.getJSONObject(i).put("text_2", telNum);
                        }
                    }
                }
                break;
        }
    }
}
